package com.stenio.fancat.pay;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stenio.fancat.common.FanCatException;
import com.stenio.fancat.common.HttpClient;
import com.stenio.fancat.form.OrderForm;
import com.stenio.fancat.pay.mapper.WxOrderMapper;
import com.stenio.fancat.util.XmlUtil;

@Component
public class Pay {
	private static final Logger logger = LoggerFactory.getLogger(Pay.class);
	public static final String SUCCESS = "SUCCESS";

	@Value("${pay.appid}")
	private String appid;
	@Value("${pay.mch-id}")
	private String mchId;
	@Value("${pay.key}")
	private String key;
	@Value("${pay.notice-url}")
	private String noticeUrl;
	@Autowired
	private WxOrderMapper wxOrderMapper;

	public OrderResult placeOrder(OrderForm form) throws FanCatException {
		Order order = new Order();
		order.setAppid(appid);
		order.setMch_id(mchId);
		order.setNonce_str(RandomStringUtils.random(8, true, true));
		order.setBody(form.getBody());
		order.setTotal_fee(form.getFee());
		order.setTrade_type("NATIVE");
		order.setSpbill_create_ip(form.getIp());
		order.setOut_trade_no(form.getRechOrderNO());
		order.setNotify_url(noticeUrl);
		order.setSign(new Md5Encryptor().encrypt(order, key));

		String xmlBody = XmlUtil.fromBean(order);
		HttpClient httpClient = new HttpClient();
		String result = httpClient.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlBody);
		try {
			OrderResult orderResult = XmlUtil.toBean(result, OrderResult.class);
			logger.info("==>{}" , orderResult.toString());
			if (SUCCESS.equals(orderResult.getResult_code())) {
				order.setStatus(0);
				wxOrderMapper.insert(order);
				return orderResult;
			}
			throw new FanCatException(orderResult.getReturn_msg());
		} catch (IllegalAccessException | InstantiationException e) {
			throw new FanCatException("下单时出错");
		}
	}

	public Integer processNotice(Notice notice) throws FanCatException {
		String sign = new Md5Encryptor().encrypt(notice, key);
		if (!notice.getSign().equals(sign)) {
			throw new FanCatException("sign签名不正确");
		}
		Order order = new Order();
		if (SUCCESS.equals(notice.getReturn_code())) {
			order.setStatus(1);
		} else {
			order.setStatus(2);
		}
		return wxOrderMapper.update(order, new EntityWrapper<Order>().eq("total_fee", notice.getTotal_fee())
				.eq("status", 0).eq("out_trade_no", notice.getOut_trade_no()));
	}
}
